﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GolfLeague.Models
{
    public class PlayerInterface
    {
        GolfLeagueEntities golfDB = new GolfLeagueEntities();

        public IQueryable<Player> GetAllPlayers()
        {
            return from playerEntity in golfDB.Players
                   orderby playerEntity.LastName
                   select playerEntity;
        }

        public Player GetPlayer(int playerID)
        {
            var playerQuery = from playerEntity in golfDB.Players
                              where playerEntity.PlayerID.Equals(playerID)
                              select playerEntity;

            return playerQuery.FirstOrDefault();
        }

        public PlayerHandicap GetPlayersCurrentHandicap(int playerID)
        {
            return (from playerEntity in golfDB.PlayerHandicaps
                    where playerEntity.PlayerID.Equals(playerID)
                    orderby playerEntity.CreatedOn descending
                    select playerEntity).FirstOrDefault();
        }

        public PlayerHandicap GetPlayersPreviousHandicap(int playerID)
        {
            var score = from playerEntity in golfDB.PlayerHandicaps
                        where playerEntity.PlayerID.Equals(playerID)
                        orderby playerEntity.CreatedOn descending
                        select playerEntity;
            if (score.Count() > 1)
                return score.ElementAt(1);
            else
                return null;
        }

        public void AddPlayer(Player player)
        {
            golfDB.Players.AddObject(player);
        }

        public void DeletePlayer(Player player)
        {
            golfDB.Players.DeleteObject(player);
        }

        public void Save()
        {
            golfDB.SaveChanges();
        }

    }
}